//
/**
 * Filename: fig10-8_sleep2.c
 * Author:   csbonkers
 * Contact:  forever65535@qq.com
 * Date:     2021/6/19
 * Description:
 *    sleep的另一个不完善的实现
 *    问题：
 *       如果其他信号处理函数运行期间又发生了定时器超时信号，导致其他信号处理函数过早返回
 */
#include "apue.h"
#include <setjmp.h>

static jmp_buf env_alrm;

static unsigned int sleep2(unsigned int secs);

static void sig_alrm(int signo);
static void sig_int(int signo);

int main(int argc, char *argv[]) {
  unsigned int unslept;
  if (signal(SIGINT, sig_int) == SIG_ERR) {
    err_sys("signal(SIGINT) error");
  }
  unslept = sleep2(5);
  printf("sleep2 returned: %u\n", unslept);
  return 0;
}

unsigned int sleep2(unsigned int secs) {
  if (signal(SIGALRM, sig_alrm) == SIG_ERR) {
    return secs;
  }
  if (setjmp(env_alrm) == 0) {
    alarm(secs);// start timer
    pause();    // next caught signal wakes us up
  }
  return alarm(0);
}
void sig_alrm(int signo) {
  longjmp(env_alrm, 1);
}

void sig_int(int signo) {
  volatile int k = 0;
  printf("\nsig_oth starting\n");
  for (int i = 0; i < 300000; i++) {
    for (int j = 0; j < 4000000; j++) {
      k += i * j;
    }
  }
  printf("sig_oth finished\n");
}